
import os
from pathlib import Path
from unicodedata import category
from flask_restful import Resource
from flask import request, send_file
from modules.dataset import DatasetModel
from common.resp import ajax_success, ajax_error, ajax_data, ajax_page
from core import db, app
from datetime import datetime

# 图片
class ImageModel(db.Model):
    __tablename__ = "sys_image"

    id = db.Column(db.Integer, autoincrement=True, primary_key=True)
    name = db.Column(db.String(100), nullable=False, index=True) # 图片名称
    ds_id = db.Column(db.Integer, nullable=True, index=True)  # 数据集
    camera_id = db.Column(db.Integer, nullable=True)  # 摄像机
    hash = db.Column(db.String(100), nullable=True, index=True)  # 图片哈希值
    annotations = db.Column(db.JSON, default=list)  # YOLO格式标注数据
    status = db.Column(db.String(10), default="0")  #状态 0未标识 1已标识 2已审核
    category = db.Column(db.String(10), default="train")  # 类别 train训练 test测试 val验证
    create_time = db.Column(db.DateTime, nullable=True, default=datetime.now)
    update_time = db.Column(db.DateTime, nullable=True, default=datetime.now, onupdate=datetime.now)

    def to_json(self):
        return {
            "id": self.id,
            "name": self.name,
            "ds_id": self.ds_id,
            "camera_id": self.camera_id,
            "hash": self.hash,
            "annotations": self.annotations,
            "status": self.status,
            "category": self.category,
            "create_time": self.create_time.strftime("%Y-%m-%d %H:%M:%S"),
            "update_time": self.update_time.strftime("%Y-%m-%d %H:%M:%S"),
        }

class ImageResource(Resource):
    def get(self):
        query = request.args;
        filters = []
        if query.get('name'):
            filters.append(ImageModel.name.like('%' + query['name'] + '%'))
        if query.get('ds_id'):
            filters.append(ImageModel.ds_id == int(query['ds_id']))
        if query.get('camera_id'):
            filters.append(ImageModel.camera_id == int(query['camera_id'])) 
        if query.get('status'):
            filters.append(ImageModel.status == query['status'])
        if query.get('category'):
            filters.append(ImageModel.category == query['category'])

        paginate = ImageModel.query.filter(
            *filters).paginate(
            page=int(query.get('page', 1)), per_page=int(query.get('limit', 10)), error_out=False)

        return ajax_page([item.to_json() for item in paginate.items], paginate.total)

    def post(self):
        if not request.files.get('file'):
            return ajax_error('图片文件不能为空')

        ds_id = request.form.get('ds_id')
        if not ds_id:
            return ajax_error('数据集不能为空')

        camera_id = request.form.get('camera_id')
        if not camera_id:
            return ajax_error('摄像机不能为空')

        dataset = DatasetModel.query.get_or_404(ds_id)
        imgPath = os.path.join(app.config['DATASET_PATH'], dataset.path)
        if not os.path.exists(imgPath):
            os.major(imgPath)

        file = request.files['file']
        filename = datetime.datetime.now().strftime('%Y-%m-%d-%H%M%S') + '.jpg'
        file.save(os.path.join(imgPath, filename))
        
        model = ImageModel(
            ds_id = int(ds_id),
            camera_id = int(camera_id),
            name = filename,
            status = '0',
            category = request.form.get('category', 'train'),
            annotations = []
        )

        db.session.add(model)
        db.session.commit()
        return ajax_success('图片上传成功')

    def put(self):
        data = request.get_json()
        if not data.get('id'):
            return ajax_error('参数错误')

        model = ImageModel.query.get_or_404(data.get('id'))
        if not model:
            return ajax_error('图片不存在')

        if data.get('name'):
            model.name = data.get('name', model.name)
        if data.get('status'):
            model.status = data.get('status', model.status)
        if data.get('ds_id'):
            model.ds_id = data.get('ds_id', model.ds_id)
        if data.get('camera_id'):
            model.camera_id = data.get('camera_id', model.camera_id)
        if data.get('annotations'):
            model.annotations = data.get('annotations', model.annotations)    

        db.session.add(model)
        db.session.commit()
        return ajax_success('摄像机更新成功')



class ImageDetail(Resource):
    def get(self, id):
        if id:
            model = ImageModel.query.get_or_404(id)
            return ajax_data(model.to_json())
        else:
            return ajax_error('参数错误')

    def delete(self, id):
        image = ImageModel.query.get_or_404(id)
        dataset = DatasetModel.query.get_or_404(image.ds_id)
        imgPath = os.path.join(app.config['DATASET_PATH'], dataset.path, image.name)
        if os.path.exists(imgPath):
            os.remove(imgPath)

        db.session.delete(image)
        db.session.commit()
        return ajax_success('图片删除成功')

@app.route("/images/view/<int:id>", methods=['GET'])
def view_image(id):
    image = ImageModel.query.get_or_404(id)
    if not image:
        return ajax_error('图片不存在') 

    dataset = DatasetModel.query.get_or_404(image.ds_id)
    imgPath = Path(app.config['DATASET_PATH']) / dataset.path / image.name
    print(imgPath)
    return send_file(imgPath.resolve(), mimetype='image/jpeg')



@app.route("/images/move/<string:category>/<string:imageIds>", methods=['GET'])
def move_image(category, imageIds):
    ids = imageIds.split(',')
    for id in ids:
        image = ImageModel.query.get_or_404(id)
        if not image:
            return ajax_error('图片不存在') 
        image.category = category
        db.session.add(image)
    db.session.commit()
    return ajax_success('图片转移成功')


@app.route("/images/check/<string:status>/<string:imageIds>", methods=['GET'])
def check_image(status, imageIds):
    ids = imageIds.split(',')
    for id in ids:
        image = ImageModel.query.get_or_404(id)
        if not image:
            return ajax_error('图片不存在') 
        image.status = status
        db.session.add(image)
    db.session.commit()
    return ajax_success('图片审核成功')
